package org.nerve.study.sprider.common;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.db.DatabaseType;
import com.j256.ormlite.db.MysqlDatabaseType;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import org.apache.poi.ss.formula.functions.T;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Properties;

/**
 * org.nerve.study.sprider.common
 * Created by zengxm on 2016/3/17 0017.
 */
public final class DBUtil {

	private static ConnectProperties connectProperties;
	private static ConnectionSource source;

	public static class ConnectProperties{
		public String url;
		public String driver;
		public String user;
		public String password;
	}

	/**
	 * 初始化
	 */
	public static void initLiteJDBC() throws SQLException {
		ConnectProperties cp=getConnectProperties();
		if(source!=null)
			source.closeQuietly();
		source=new JdbcPooledConnectionSource(cp.url,cp.user,cp.password, new MysqlDatabaseType());
	}

	public static <T extends Serializable> Dao<T, Long> getDao(Class<T> t) throws SQLException {
		if(source==null || !source.isOpen())
			initLiteJDBC();

		return DaoManager.createDao(source, t);
	}

	public static ConnectProperties getConnectProperties(){
		if(connectProperties==null){
			//从配置文件中读取
			try{
				Properties properties=new Properties();
				properties.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));

				connectProperties=new ConnectProperties();
				connectProperties.url=properties.getProperty("jdbc.url","jdbc:mysql://localhost/test");
				connectProperties.driver=properties.getProperty("jdbc.driver","com.mysql.jdbc.Driver");
				connectProperties.user=properties.getProperty("jdbc.user","root");
				connectProperties.password=properties.getProperty("jdbc.password","");
			}catch (Exception e){
				e.printStackTrace();
			}
		}

		return connectProperties;
	}
}
